<template>
    <div class="mall-container">
        <!-- 顶部导航栏 -->
        <van-nav-bar
            title="小坤商城"
            background="#FFEEF2"
            title-color="#E63946"
            right-icon="search"
            @click-right="showSearch"
        />

        <!-- 分类栏（按钮形式） -->
        <div class="category">
            <van-button
                class="category-btn"
                v-for="(item, index) in categoryList"
                :key="index"
                :color="item.color"
                @click="handleCategoryClick(item.name)"
            >
                {{ item.name }}
            </van-button>
        </div>

        <!-- 轮播图 -->
        <div class="swipe-container">
            <van-swipe :autoplay="3000" lazy-render class="custom-swipe">
                <van-swipe-item v-for="image in bannerList" :key="image" class="swipe-item">
                    <img :src="image" class="swipe-img"/>
                </van-swipe-item>
            </van-swipe>
        </div>

        <!-- 热销推荐：添加唯一id "hot-goods-section" 作为定位目标 -->
        <div class="goods-section" id="hot-goods-section">
            <div class="section-header">
                <h3 class="section-title">热销推荐</h3>
                <van-tag type="primary" color="#FFA500">HOT</van-tag>
            </div>
            <!-- 新的列表式布局 -->
            <div class="goods-list">
                <div
                    class="goods-item"
                    v-for="(goods, index) in hotGoodsList"
                    :key="index"
                    @click="goToDetail(goods)"
                >
                    <!-- 商品图片 -->
                    <van-image
                        :src="goods.image1"
                        class="goods-img"
                        fit="cover"
                        radius="8"
                    />
                    <!-- 商品信息（名称、价格、操作） -->
                    <div class="goods-info">
                        <h4 class="goods-title">{{ goods.productName }}</h4>
                        <div class="goods-price">
                            <span class="now-price">¥{{ goods.actualPrice }}</span>
                            <span class="old-price">¥{{ goods.listPrice }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新品上架（结构与“热销推荐”一致，仅替换循环数组为newGoodsList） -->
        <div class="goods-section">
            <div class="section-header">
                <h3 class="section-title">新品上架</h3>
                <van-tag type="primary" color="#FFA500">NEW</van-tag>
            </div>
            <div class="goods-list">
                <div
                    class="goods-item"
                    v-for="(goods, index) in newGoodsList"
                    :key="index"
                    @click="goToDetail(goods)"
                >
                    <van-image
                        :src="goods.image1"
                        class="goods-img"
                        fit="cover"
                        radius="8"
                    />
                    <div class="goods-info">
                        <h4 class="goods-title">{{ goods.productName }}</h4>
                        <div class="goods-price">
                            <span class="now-price">¥{{ goods.actualPrice }}</span>
                            <span class="old-price">¥{{ goods.listPrice }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <tabbar/>

        <!-- 悬浮广告 -->
        <div class="float-ad-container">
            <!-- 广告缩略图（始终显示） -->
            <div
                class="ad-thumbnail"
                @click="toggleAdDetail"
                :class="{ 'active': isAdDetailVisible }"
            >
                <van-image
                    src="https://wdjichi.oss-cn-hangzhou.aliyuncs.com/store/%E5%B9%BF%E5%91%8A%E4%BD%8D%E6%8B%9B%E7%A7%9F.png"
                    alt="限时优惠广告"
                    round
                />
                <span class="ad-badge">特惠</span>
            </div>

            <!-- 广告详情（点击后展开） -->
            <div
                class="ad-detail"
                v-if="isAdDetailVisible"
                :class="{ 'fade-in': isAdDetailVisible }"
            >
                <div class="ad-close" @click="toggleAdDetail">
                    <van-icon name="cross" size="18" />
                </div>
                <van-image
                    src="https://wdjichi.oss-cn-hangzhou.aliyuncs.com/store/%E5%B9%BF%E5%91%8A%E4%BD%8D%E6%8B%9B%E7%A7%9F.png"
                    alt="广告位招租"
                    class="ad-detail-img"
                />
                <div class="ad-detail-content">
                    <h3 class="ad-title">广告位招租</h3>
                    <p class="ad-desc">广告位招租!!!</p>
                    <van-button
                        class="ad-button"
                        type="primary"
                        color="#E63946"
                        @click="goToAdPage"
                    >
                        立即查看
                    </van-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import tabbar from '@/components/tab-bar.vue'
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from "vue-router";
import axios from '@/utils/axios.js'
import { showToast } from 'vant';
import { Icon } from 'vant';

// 广告相关状态
const isAdDetailVisible = ref(false);

// 切换广告详情显示/隐藏
const toggleAdDetail = () => {
    isAdDetailVisible.value = !isAdDetailVisible.value;
};

// 跳转到广告页面
const goToAdPage = () => {
    showToast('跳转到广告活动页面');
    isAdDetailVisible.value = false;
};

onMounted(() => {
    init()
})
const pages = reactive({
    page: 1,
    limit: 100,
})
const init = () => {
    axios.post("/api/productsPage?page=" + (pages.page++) + "&limit=" + pages.limit)
        .then(res => {
            // 处理热销推荐商品的价格
            hotGoodsList.value = res.data.records.map(goods => {
                return {
                    ...goods,
                    actualPrice: Math.floor(goods.actualPrice) // 向下取整为整数
                };
            });
            // 处理新品上架商品的价格
            newGoodsList.value = res.data.records.map(goods => {
                return {
                    ...goods,
                    actualPrice: Math.floor(goods.actualPrice) // 向下取整为整数
                };
            });
        })
}
const router = useRouter(); // 初始化路由实例
const goBack = () => {
    router.back();
}
const goToDetail = (goods) => {
    // 用router.push跳转到详情页，并通过params传递商品id
    router.push({
        name: 'productsDetail', // 对应详情页路由的name
        params: { productId: goods.productId } // 传递商品id（和路由配置的:id对应）
    });
};
// 轮播图
const bannerList = [
    'https://ts1.tc.mm.bing.net/th/id/OIP-C.t5R4UVLnG3Cjr9l6N3FouwHaHa?w=180&h=211&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2',
    'https://tse2-mm.cn.bing.net/th/id/OIP-C._mOSvKqjSSDw_-MfDYRCpgHaHa?w=191&h=191&c=7&r=0&o=5&pid=1.7',
    'https://tse3-mm.cn.bing.net/th/id/OIP-C.eFs0hoj5lop_tm82tuJRMAHaJm?w=144&h=187&c=7&r=0&o=5&pid=1.7',
];
// 分类
const categoryList = ref([
    { name: '近期热卖', color: '#FFA500' },
    { name: '我的订单', color: '#FFA500' },
    { name: '地址管理', color: '#FFA500' },
    { name: '寻求客服', color: '#FFA500' },
]);

const hotGoodsList = ref([
    {
        productId: 0,
        productName: '',
        listPrice: 0,
        image1: '',
        image2: '',
        image3: '',
        shortDesc: '',
        longDesc: '',
        listedAt: '',
        stock: 0,
        collects: 0,
        sales: 0,
        discount: 0,
        actualPrice: 0,
    }
]);

const newGoodsList = ref([
    {
        productId: 0,
        productName: '',
        listPrice: 0,
        image1: '',
        image2: '',
        image3: '',
        shortDesc: '',
        longDesc: '',
        listedAt: '',
        stock: 0,
        collects: 0,
        sales: 0,
        discount: 0,
        actualPrice: 0,
    }
]);

// 分类按钮点击事件处理：重点修改“近期热卖”的逻辑
const handleCategoryClick = (categoryName) => {
    switch (categoryName) {
        case '近期热卖':
            // 1. 找到“热销推荐”区域（通过id定位）
            const hotGoodsSection = document.getElementById('hot-goods-section');
            // 2. 平滑滚动到该区域（behavior: 'smooth' 实现流畅滚动）
            if (hotGoodsSection) {
                hotGoodsSection.scrollIntoView({
                    behavior: 'smooth', // 平滑滚动
                    block: 'start' // 滚动后目标区域顶部对齐视口顶部
                });
            }
            break;
        case '我的订单':
            router.push('/order')
            break;
        case '地址管理':
            router.push('/Address');
            break;
        case '寻求客服':
            window.location.href ="https://www.deepseek.com/?code=DEEPSEEK30"
            break;
        default:
            break;
    }
};

// 状态管理
const activeTab = ref(0);
const showSearch = () => showToast('搜索功能待开发');

</script>

<style scoped>
.mall-container {
    background: linear-gradient(to bottom, #FFF9FB, #FFE5EC);
    min-height: 100vh;
    padding-bottom: 60px;
    position: relative; /* 为悬浮广告提供定位参考 */
}

/* 分类栏 */
.category {
    display: flex;
    justify-content: space-around;
    padding: 15px 0;
    background-color: #fff;
    border-radius: 12px;
    margin: 0 10px 15px 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-btn {
    flex: 1;
    margin: 0 5px;
    border-radius: 20px !important;
}

/* 轮播图 */
/* 轮播图容器，设置宽高比为 16:9 */
.swipe-container {
    width: 100%;
    /* aspect-ratio 表示宽高比，16/9 即 16:9 */
    aspect-ratio: 16 / 9;
    overflow: hidden;
    margin-bottom: 16px;
}
/* 轮播图组件，使其占满容器 */
.custom-swipe {
    width: 100%;
    height: 100%;
}
/* 轮播图项，使其占满容器 */
.swipe-item {
    width: 100%;
    height: 100%;
}
/* 轮播图图片，保持比例填充容器 */
.swipe-img {
    width: 100%;
    height: 100%;
    /* 保持图片比例，填充容器，超出部分裁剪 */
    object-fit: cover;
}

/* 商品列表 */
.goods-section {
    padding: 0 10px;
    margin-bottom: 20px;
}

.section-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0 8px 0 0;
    padding-left: 6px;
    border-left: 4px solid #FF8FA3;
}

.goods-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: space-between;
}

.goods-item {
    width: calc(50% - 5px);
    background-color: #fff;
    border: 1px solid #eee;
    border-radius: 8px;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: transform 0.3s ease;
}

.goods-item:nth-child(4n + 2) {
    margin-top: 20px;
}

.goods-item:nth-child(4n + 3) {
    margin-top: 20px;
}

.goods-item:hover {
    transform: translateY(-5px);
}

.goods-img {
    width: 100%;
    height: 120px;
    border-radius: 8px;
    margin-bottom: 8px;
}

.goods-info {
    width: 100%;
    text-align: center;
}

.goods-title {
    font-size: 14px;
    color: #333;
    margin: 8px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.goods-price {
    display: flex;
    justify-content: center;
    align-items: baseline;
    margin: 4px 0;
}

.now-price {
    font-size: 16px;
    color: #E63946;
    font-weight: 600;
    margin-right: 6px;
}

.old-price {
    font-size: 12px;
    color: #999;
    text-decoration: line-through;
}

.add-cart-btn {
    width: 80%;
    margin-top: 8px;
    border-radius: 20px !important;
    font-size: 12px;
}

/* 悬浮广告样式 */
.float-ad-container {
    position: fixed;
    right: 20px;
    bottom: 90px; /* 避开底部导航 */
    z-index: 100; /* 确保在其他内容上方 */
}

/* 广告缩略图 */
.ad-thumbnail {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    box-shadow: 0 4px 12px rgba(230, 57, 70, 0.3);
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    background-color: white;
    padding: 5px;
}

.ad-thumbnail.active {
    transform: scale(1.1);
    box-shadow: 0 6px 16px rgba(230, 57, 70, 0.4);
}
</style>